<template>
  <div class="w-full">
    <Editor v-model="content" :init="myTinyInit"></Editor>
    <a-modal v-model:visible="visible" @before-ok="onOk" draggable width="1000px">
      <template #title>
        <a-radio-group v-model="type" type="button">
          <a-radio value="goods">插入商品</a-radio>
          <a-radio value="coupon">插入券/会场</a-radio>
        </a-radio-group>
      </template>
      <template v-if="type === 'goods'">
        <div>
          <a-form :model="goodsForm" layout="inline" size="small" auto-label-width>
            <a-form-item hide-label field="goodsStyle">
              <a-select placeholder="选择商品模板" v-model="goodsForm.goodsStyle" class="w-34n" allow-clear>
                <a-option v-for="(item, index) in bestMaterialTemplate" :key="item.value" :value="item.content">
                  <a-popover position="right">
                    <p>{{ item.label }}</p>
                    <template #content>
                      <img :src="thumbnail[index]" class="w-50n" style="object-fit: contain" />
                    </template>
                  </a-popover>
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="sourceType" hide-label v-if="goodsForm.goodsStyle">
              <a-select v-model="goodsForm.sourceType" placeholder="选择商品平台" class="w-34n" allow-clear>
                <a-option v-for="item in platformList" :key="item.id" :value="item.id" :label="item.title"></a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="goodsId" hide-label v-if="goodsForm.sourceType">
              <a-input v-model="goodsForm.goodsId" placeholder="请输入商品ID" allow-clear />
            </a-form-item>
            <a-form-item field="activityId" hide-label v-if="goodsForm.sourceType">
              <a-input v-model="goodsForm.activityId" placeholder="请输入券ID" allow-clear />
            </a-form-item>
            <a-form-item hide-label v-if="goodsForm.sourceType">
              <a-button :loading="getGoodsLoading" type="primary" @click="getGoods">
                <template #icon> <icon-find-replace /></template>
                获取商品
              </a-button>
            </a-form-item>
          </a-form>
          <a-table :columns="columns" :data="tableData" class="mt-10" :pagination="false">
            <template #picUrl="{ record }">
              <ImgHoverPreview :width="50" :url="record.picUrl" />
            </template>
            <template #action="{ rowIndex }">
              <a-button type="text" size="small" @click="openSetGoods(rowIndex)"> 设置 </a-button>
              <a-popconfirm content="是否确认删除?" @ok="onDeleteItem(rowIndex)">
                <a-button type="text" size="small"> 删除 </a-button>
              </a-popconfirm>
            </template>
          </a-table>
        </div>
      </template>
      <template v-else>
        <a-form :model="couponForm" size="small" auto-label-width>
          <a-form-item field="sourceType" label="所属平台">
            <a-select v-model="couponForm.sourceType" placeholder="选择券/会场/商品所属平台" allow-clear>
              <a-option v-for="item in platformList" :key="item.id" :value="item.id" :label="item.title"></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="背景图" field="goodsCouponBg">
            <MsUpload v-model="couponForm.goodsCouponBg"></MsUpload>
          </a-form-item>
          <a-form-item field="opentype" label="打开方式">
            <a-select placeholder="选择打开方式" v-model="couponForm.opentype" allow-clear>
              <a-option v-for="item in openArr" :key="item.id" :value="item.id">
                {{ item.title }}
              </a-option>
            </a-select>
          </a-form-item>
          <template v-if="couponForm.opentype === 1">
            <a-form-item field="itemsourceid" label="商品ID">
              <a-input v-model="couponForm.itemsourceid" placeholder="请输入商品ID" allow-clear />
            </a-form-item>
          </template>
          <template v-else>
            <a-form-item
              field="url"
              :label="couponForm.opentype === 2 ? 'H5链接' : couponForm.opentype === 3 ? '会场ID/链接' : ''"
            >
              <a-input
                v-model="couponForm.url"
                :placeholder="`请输入${
                  couponForm.opentype === 2 ? 'H5链接' : couponForm.opentype === 3 ? '会场ID/链接' : ''
                }`"
                allow-clear
              />
            </a-form-item>
          </template>
          <template v-if="couponForm.opentype === 3 || couponForm.opentype === 4">
            <a-form-item field="isturning" label="是否需要转链">
              <a-space>
                <a-radio-group v-model="couponForm.isturning">
                  <a-radio :value="1">需要</a-radio>
                  <a-radio :value="0">不需要</a-radio>
                </a-radio-group>
                <span class="font-bold text666 mb-4">(社群中的链接请勾选不需要)</span>
              </a-space>
            </a-form-item>
          </template>
        </a-form>
      </template>
    </a-modal>
    <a-modal v-model:visible="setGoodsVisible" title="商品设置" @ok="setGoods" draggable>
      <a-form size="small" auto-label-width :model="setGoodsForm">
        <a-form-item field="goodsCouponDesc" label="券描述">
          <a-input v-model="setGoodsForm.goodsCouponDesc" placeholder="请输入券描述" allow-clear />
        </a-form-item>
        <a-form-item field="goodsDesc" label="商品推荐语">
          <a-input v-model="setGoodsForm.goodsDesc" placeholder="请输入推荐语" allow-clear />
        </a-form-item>
        <a-form-item field="opentype" label="打开方式">
          <a-select placeholder="选择打开方式" v-model="setGoodsForm.opentype" allow-clear>
            <a-option v-for="item in openArr" :key="item.id" :value="item.id">
              {{ item.title }}
            </a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { bestMaterialTemplateTree, goodsDetails } from '@/apis'
import { usePlatform } from '@/hooks/app'
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/icons/default/icons'
import 'tinymce/themes/silver'
import 'tinymce/models/dom/model'
import 'tinymce/skins/ui/oxide/skin.css'
import 'tinymce/skins/ui/oxide-dark/skin.css'
import { uploadImageTinymce, uploadVideoTinymce } from '@/apis'
import { Notification } from '@arco-design/web-vue'

//按需引入插件
import 'tinymce/plugins/image'
import 'tinymce/plugins/media'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/link'
import '../../../public/tinymce/langs/zh_CN.js'
import { deleteEmpty } from '@/utils/common'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  plugins: {
    type: [String, Array],
    default: 'lists link image media'
  },
  toolbar: {
    type: [String, Array],
    default:
      'bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | image media custom | 135'
  },
  height: {
    type: [String, Number],
    default: '100%'
  }
})
const emit = defineEmits(['input'])
const content = ref()
const visible = ref(false)
const type = ref('goods')
const bestMaterialTemplate = ref([])
const formRef = ref()
const thumbnail = [
  'https://images.maishou88.com/admin/topic_background_image/20220617/20220617180251_1990.jpg',
  'https://images.maishou88.com/admin/topic_background_image/20220617/20220617180049_6965.jpg',
  'https://images.maishou88.com/admin/topic_background_image/20220617/20220617180156_2444.jpg'
]

;(async function () {
  const res = await bestMaterialTemplateTree()
  bestMaterialTemplate.value = res.data.list
})()

const { platformList, getPlatformList } = usePlatform()
getPlatformList()

let editor135 = null
const onContentFrom135 = (event) => {
  if (typeof event.data !== 'string') {
    if (event.data.ready) {
      editor135.postMessage(JSON.parse(JSON.stringify(content.value)), '*')
    }
    return
  }

  if (event.data.indexOf('<') !== 0) return

  content.value = event.data
  window.removeEventListener('message', onContentFrom135)
}
const getContainerE = ref()
onMounted(() => {
  getContainerE.value = tinymce.activeEditor.getContainer()
})

watch(
  () => props.height,
  (value) => {
    nextTick(() => {
      tinymce.activeEditor.getContainer().setAttribute('style', `height: ${value}px;`)
    })
  }
)

const myTinyInit = reactive({
  width: '100%',
  height: props.height,
  branding: false,
  menubar: false,
  resize: false,
  language: 'zh_CN',
  skin_url: '/tinymce/skins/ui/oxide', //手动引入
  content_css: '/tinymce/skins/content/default/content.css', //手动引入
  toolbar_mode: 'wrap',
  plugins: props.plugins,
  toolbar: props.toolbar,
  //图片上传方法（注意！！：要使用 promise 对象中的 resolve 返回图片路径，否则会报错）
  images_upload_handler: (blobInfo) =>
    new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('photoImg', blobInfo.blob(), blobInfo.filename())
      uploadImageTinymce(formData)
        .then((res) => {
          resolve(res.data.url)
        })
        .catch(() => {
          reject(false)
        })
    }),
  file_picker_callback: (callback, value, meta) => {
    const filetype = '.mp4,.mkv, .avi,.wmv, .rmvb,.mov,.mpg,.mpeg,.webm, .jpg, .jpeg, .png, .gif' //限制文件的上传类型
    const inputElem = document.createElement('input') //创建文件选择
    inputElem.setAttribute('type', 'file')
    inputElem.setAttribute('accept', filetype)
    inputElem.click()
    inputElem.onchange = async () => {
      let res = null
      const file = inputElem.files[0] //获取文件信息
      const params = new FormData()
      params.append('photoImg', file)
      if (meta.filetype === 'media') {
        res = await uploadVideoTinymce(params)
        callback(res.data.videoLink)
      } else if (meta.filetype === 'image') {
        res = await uploadImageTinymce(params)
        callback(res.data.url)
      }
    }
  },
  setup: (editor) => {
    editor.ui.registry.addIcon(
      'editor135',
      '<img src="http://static.135editor.com/img/icons/editor-135-icon.png" alt="">'
    )
    editor.ui.registry.addIcon(
      'goods',
      '<svg t="1690249218962" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5025" xmlns:xlink="http://www.w3.org/1999/xlink" width="18" height="18"><path d="M256.727757 323.584c16.9984 0 30.72-13.7216 30.72-30.72 0-125.952 102.4-228.352 228.352-228.352s228.352 102.4 228.352 228.352c0 16.9984 13.7216 30.72 30.72 30.72s30.72-13.7216 30.72-30.72c0-159.744-130.048-289.792-289.792-289.792S226.007757 133.12 226.007757 292.864c0 16.9984 13.7216 30.72 30.72 30.72zM895.089357 358.4H129.137357C51.108557 358.4-9.102643 431.104 1.137357 512.8192l37.888 303.104C53.975757 934.912 150.026957 1024 263.690957 1024h496.8448c113.664 0 209.5104-89.088 224.4608-208.0768l37.888-303.104c10.24-81.7152-49.7664-154.4192-127.7952-154.4192zM279.665357 692.224c-41.3696 0-74.752-33.3824-74.752-74.752s33.3824-74.752 74.752-74.752 74.752 33.3824 74.752 74.752-33.3824 74.752-74.752 74.752z m495.616 0c-41.3696 0-74.752-33.3824-74.752-74.752s33.3824-74.752 74.752-74.752 74.752 33.3824 74.752 74.752-33.3824 74.752-74.752 74.752z" p-id="5026" fill="#222f3e"></path></svg>'
    )
    editor.ui.registry.addButton('135', {
      icon: 'editor135',
      tooltip: '打开135编辑器',
      onAction: () => {
        editor135 = window.open('https://www.135editor.com/simple_editor.html?callback=true&appkey=')
        window.removeEventListener('message', onContentFrom135)
        window.addEventListener('message', onContentFrom135, false)
      }
    })
    editor.ui.registry.addButton('custom', {
      icon: 'goods',
      tooltip: '插入/商品或券',
      onAction: () => {
        visible.value = true
      }
    })
  }
})

const initContent = computed(() => {
  return props.modelValue
})

onMounted(() => {
  tinymce.init({})
})

watch(
  initContent,
  (newVal) => {
    content.value = newVal
  },
  { deep: true, immediate: true }
)

watch(
  content,
  (newVal) => {
    emit('input', newVal)
  },
  { deep: true }
)

const goodsForm = ref({
  goodsStyle: '',
  sourceType: '',
  goodsId: '',
  activityId: ''
})
const couponForm = ref({
  sourceType: '',
  goodsCouponBg: '',
  opentype: 3,
  isturning: 1,
  itemsourceid: '',
  url: ''
})
const setGoodsForm = ref({
  goodsCouponDesc: '',
  goodsDesc: '',
  opentype: ''
})
const setGoodsVisible = ref(false)
const getGoodsLoading = ref(false)
const tableData = ref([])
const current = ref()
const columns = ref([
  {
    title: '商品名称',
    width: 150,
    dataIndex: 'title',
    tooltip: true,
    ellipsis: true
  },
  {
    title: '商品图',
    width: 90,
    slotName: 'picUrl'
  },
  {
    title: '券后价',
    dataIndex: 'actualPrice',
    width: 120
  },
  {
    title: '操作',
    width: 130,
    fixed: 'right',
    align: 'center',
    slotName: 'action'
  }
])
const openArr = [
  {
    title: '商品详情',
    id: 1
  },
  {
    title: '其他APP会场/领券',
    id: 3
  },
  {
    title: 'H5页面/买手妈妈APP会场',
    id: 2
  }
]
// 获取商品
const getGoods = () => {
  getGoodsLoading.value = true
  const { goodsId, sourceType, activityId, goodsStyle } = goodsForm.value
  const goodsIdArr = goodsId.split(',')
  let flag = 0
  goodsIdArr.forEach(async (item) => {
    goodsDetails(
      deleteEmpty({
        goodsId: item,
        sourceType,
        activityId
      })
    )
      .then((res) => {
        const result = res.data
        result['goodsStyle'] = goodsStyle
        result['opentype'] = 1
        result['goodsCouponDesc'] = result['goodsDesc'] = ''
        tableData.value.push(result)
      })
      .catch(() => {
        Notification.error({
          title: '温馨提示',
          content: `商品ID：【${item}】获取失败`,
          closable: true,
          duration: 10000
        })
      })
      .finally(() => {
        flag++
        if (flag === goodsIdArr.length) {
          getGoodsLoading.value = false
        }
      })
  })
}

// 删除商品
const onDeleteItem = (index) => {
  tableData.value.splice(index, 1)
}
// 打开商品设置框
const openSetGoods = (index) => {
  current.value = index
  const { opentype, goodsCouponDesc, goodsDesc } = tableData.value[index]
  setGoodsForm.value.opentype = opentype
  setGoodsForm.value.goodsCouponDesc = goodsCouponDesc
  setGoodsForm.value.goodsDesc = goodsDesc
  setGoodsVisible.value = true
}
// 确认设置商品
const setGoods = () => {
  const { opentype, goodsCouponDesc, goodsDesc } = setGoodsForm.value
  tableData.value[current.value].opentype = opentype
  tableData.value[current.value].goodsCouponDesc = goodsCouponDesc
  tableData.value[current.value].goodsDesc = goodsDesc
}
const onOk = () => {
  let tempGoodsStyle = ''
  switch (type.value) {
    // 商品
    case 'goods': {
      tableData.value.forEach((el) => {
        let tempGoodsStyleCopy = el.goodsStyle
          .replace('{{data-showtype}}', el.shopType)
          .replace('{{data-opentype}}', el.opentype)
          .replace('{{data-itemsource}}', el.sourceType)
          .replace('{{data-itemsourceid}}', el.goodsId)
          .replace('{{goodsImg}}', el.picUrl)
          .replace('{{goodsTitle}}', el.title)
          .replace('{{goodsCouponPrice}}', el.couponPrice)
          .replace('{{goodsCouponDesc}}', el.goodsCouponDesc)
          .replace('{{goodsDesc}}', el.goodsDesc)
          .replace('{{goodsActualPrice}}', el.actualPrice)
          .replace('{{goodsOriginalPrice}}', el.originalPrice)
          .replace('{{goodsShopLogo}}', el.shopLogo)
        if (el.couponPrice && el.couponPrice > 0) {
          tempGoodsStyleCopy = tempGoodsStyleCopy.replace('<!--', '').replace('-->', '')
        }
        tempGoodsStyle = tempGoodsStyle + tempGoodsStyleCopy
      })
      tinymce.activeEditor.insertContent(tempGoodsStyle)
      goodsForm.value.goodsStyle =
        goodsForm.value.sourceType =
        goodsForm.value.goodsId =
        goodsForm.value.activityId =
          ''
      tableData.value = []
      break
    }

    case 'coupon': {
      const couponStyle =
        '<p data-showtype="{{data-showtype}}" data-isturning="{{data-isturning}}" data-opentype="{{data-opentype}}" data-itemsource="{{data-itemsource}}" data-itemsourceid="{{data-itemsourceid}}" data-linktext="{{data-linktext}}" data-splicepid="{{data-splicepid}}" data-url="{{data-url}}" data-extendjson="{{data-extendjson}}" data-suppliercode="{{data-suppliercode}}" style="vertical-align:inherit;color: rgb(102, 102, 102);"><img src="{{goodsCouponBg}}" style="max-width: 100% !important;box-sizing:border-box;vertical-align: inherit; width: 100%;" /></p>'
      if (couponForm.value.url.indexOf('msmm://appView?path=') != -1) {
        couponForm.value.url = couponForm.value.url.replace('msmm://appView?path=', '')
      }
      const opentype = couponForm.value.opentype == 4 ? 3 : couponForm.value.opentype
      tempGoodsStyle = couponStyle
        .replace('{{data-opentype}}', opentype)
        .replace('{{data-itemsource}}', couponForm.value.sourceType)
        .replace('{{data-itemsourceid}}', couponForm.value.itemsourceid)
        .replace('{{data-url}}', couponForm.value.url)
        .replace('{{data-suppliercode}}', couponForm.value.suppliercode)
        .replace('{{data-isturning}}', couponForm.value.isturning)
        .replace('{{goodsCouponBg}}', couponForm.value.goodsCouponBg)
      tinymce.activeEditor.insertContent(tempGoodsStyle)
      couponForm.value.sourceType =
        couponForm.value.goodsCouponBg =
        couponForm.value.itemsourceid =
        couponForm.value.url =
          ''
      couponForm.value.opentype = 3
      couponForm.value.isturning = 1
      break
    }
  }
  return true
}

provide('formRef', formRef)
</script>
